package com.qf.fmall.utils;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.*;

@Slf4j
public class WXpayUtils {

    public static final String APPID = "wx632c8f211f8122c6";
    public static final String MCH_ID = "1497984412";
    public static final String APPKEY = "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC";

    // 统一下单接口 url
    public static final String WX_UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    // 查询订单状态的接口的url
    public static final String WX_QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";

    public static String getPayUrl(String content, String orderId, Integer totalFee) {

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appid", APPID);
        hashMap.put("mch_id", MCH_ID);
        hashMap.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
        hashMap.put("body", content);
        hashMap.put("out_trade_no", orderId);
        hashMap.put("total_fee", 1);  // 订单的金额，单位是分
        hashMap.put("notify_url", "http://47.118.45.73:8080/pay/callback");
        hashMap.put("trade_type", "NATIVE");

        // 计算签名
        String sign = createSign(hashMap);
        hashMap.put("sign", sign);

        // 将 hashMap 转换为XML 字符串
        String xmlStr = XmlUtil.mapToXmlStr(hashMap);

        //2. 发送http请求给微信支付接口
        String resultXML = HttpRequest.post((WX_UNIFIEDORDER_URL)) // 发送pos请求
                .body(xmlStr) // 设置post请求体中的数据
                .execute() // 将请求发送出去
                .body(); // 获取响应体中的数据

//        System.out.println(resultXML);
        //3. 解析响应的XML数据
        Map<String, Object> resultMap = XmlUtil.xmlToMap(resultXML);
        String url = (String) resultMap.get("code_url");

        return url;
    }

    private static String createSign(HashMap<String, Object> hashMap) {
        //1. 获取所有参数的名字 ，进行排序
        Set<String> keySet = hashMap.keySet();
        String[] keyArr = new String[keySet.size()];
        keySet.toArray(keyArr);

        Arrays.sort(keyArr);

        //2. 拼串 StringA
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < keyArr.length; i++) {
            String key = keyArr[i];
            Object value = hashMap.get(key);
            stringBuffer
                    .append(key)
                    .append("=")
                    .append(value)
                    .append("&");
        }
        String stringA = stringBuffer.toString();

        //3. 拼接自己的商户的密钥
        String stringSignTemp = stringA + "key=" + APPKEY;

        //4. 进行MD5运算
        String sign = DigestUtil.md5Hex(stringSignTemp).toUpperCase();


        return sign;


    }

    public static boolean getSatus(String orderId) {

        //1. 调用微信的查询订单状态接口，获取订单的状态
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appid", APPID);
        hashMap.put("mch_id", MCH_ID);
        hashMap.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
        hashMap.put("out_trade_no", orderId);

        // 计算签名
        String sign = createSign(hashMap);
        hashMap.put("sign", sign);

        String xmlStr = XmlUtil.mapToXmlStr(hashMap);

        //2. 发送请求
        String resultXML = HttpRequest.post(WX_QUERY_URL)
                .body(xmlStr)
                .execute()
                .body();

        //3. 解析响应的xml数据
        Map<String, Object> map = XmlUtil.xmlToMap(resultXML);
        String result = (String) map.get("trade_state");

        System.out.println(map);
        System.out.println(result);
        if ("SUCCESS".equals(result)) {

            return true;
        } else {
            return false;
        }
    }
}
